package com.cy.jt.security.util.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

public class DefaultAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication)
            throws IOException, ServletException {
        User principal = (User)authentication.getPrincipal();
        System.out.println(principal.getAuthorities() + principal.getUsername()+
                principal.getPassword());
        Object credentials = authentication.getCredentials();
        System.out.println("principal=" + principal+credentials);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
//        out.println("{\"state\":200,\"msg\":ok\"}");
        HashMap<Object, Object> map = new HashMap<>();
        map.put("state", "200");
        map.put("msg", "Login ok");
        String jsonStr = new ObjectMapper().writeValueAsString(map);
        out.println(jsonStr);
        System.out.println(jsonStr);
        out.flush();
    }
}
